const toFixedFix = function (n, prec) {
    let k = Math.pow(10, prec);
    return String(parseFloat(Math.ceil(parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k);
};
/*
  * 参数说明：
  * num：要格式化的数字
  * decimals：保留几位小数，默认2位
  * */
function numberFormat(num, decimals = 2) {
    const inNumber = (String(num)).replace(/[^0-9+-Ee.]/g, '');
    let n = !isFinite(Number(inNumber)) ? 0 : Number(inNumber);
    let prec = !isFinite(Number(decimals)) ? 0 : Math.abs(decimals);
    let sep = ',';
    let dec = '.';
    let s = [];
    s = (prec ? toFixedFix(n, prec) : String(Math.round(n))).split('.');
    let re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, '$1' + sep + '$2');
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

export { numberFormat as default };
